#!/usr/bin/env bash
#
# narsil-dnsserver.sh - Change DNS Server
# Seaton Jiang <hi@seatonjiang.com>
#
# The latest version of Narsil can be found at:
# https://github.com/seatonjiang/narsil
#
# Copyright (C) 2023 Seaton Jiang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

function narsil_dnsserver()
{
    msg_info '\n%s\n' "[${STATS}] Change DNS Server"

    narsil_dnsserver='119.29.29.29 223.5.5.5'

    if [[ ${METADATA} == "Y" ]]; then
        if [ -n "$(wget -qO- -t1 -T2 metadata.tencentyun.com)" ]; then
            dnsserver='183.60.83.19 183.60.82.98'
        fi
    fi

    if [ "${narsil_dnsserver}" != "${DNS_SERVER}" ]; then
        dnsserver=${DNS_SERVER}
    fi

    if [ ! -f /etc/cloud/cloud.cfg ]; then
        sed -i '/resolv_conf/d' /etc/cloud/cloud.cfg
    fi

    nmcli con mod "System eth0" ipv4.dns "${dnsserver}" >/dev/null 2>&1
    nmcli con mod "eth0" ipv4.dns "${dnsserver}" >/dev/null 2>&1

    sed -i '/PEERDNS=/d' /etc/sysconfig/network-scripts/ifcfg-eth0
    echo "PEERDNS=no" >> /etc/sysconfig/network-scripts/ifcfg-eth0

    systemctl restart NetworkManager.service

    if [[ ${VERIFY} == "Y" ]]; then
        msg_notic '\n%s\n' "• File Content: /etc/resolv.conf"
        grep -Ev '^#|^$' /etc/resolv.conf | uniq
    else
        msg_succ '%s\n' "Success, this operation is completed!"
    fi

    sleep 1

    ((STATS++))
}
